package JDK常用类库.stream;

import org.junit.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @Author：russ
 * @Date：2023/8/29
 * @apiNote：
 */
public class DateTimeStructTest {
    @Test
    public void test1() {
        long t = 1612345678L;
        String s = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime dateTime = instantToLocalDateTimeBySecond(t, s);
        System.out.println(dateTime);
        long h = 1612345678000L;
        LocalDateTime dateTime1 = instantToLocalDateTimeByMilli(h, s);
        System.out.println(dateTime1);
        System.out.println(localDateTimeToString(dateTime, s));
    }

    /**
     * 将时间戳转为LocalDateTime类型的自定义格式时间
     * @param time 传入的时间戳必须为秒
     * @param pattern 传入的时间格式
     */
    public static LocalDateTime instantToLocalDateTimeBySecond(long time, String pattern){
        Instant instant = Instant.ofEpochSecond(time);
        return instantToLocalDateTimeHelper(instant,pattern);
    }

    /**
     * 将时间戳转为LocalDateTime类型的自定义格式时间
     * @param time 传入的时间戳必须为毫秒
     * @param pattern 传入的时间格式
     */
    public static LocalDateTime instantToLocalDateTimeByMilli(long time, String pattern){
        Instant instant = Instant.ofEpochMilli(time);
        return instantToLocalDateTimeHelper(instant,pattern);
    }

    private static LocalDateTime instantToLocalDateTimeHelper(Instant instant, String pattern){
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String formattedDateTime = dateTime.format(formatter);
        LocalDateTime res = LocalDateTime.parse(formattedDateTime,formatter);
        return res;
    }

    /**
     * 将LocalDateTime转为String类型
     */
    public static String localDateTimeToString(LocalDateTime dateTime, String pattern){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String res = dateTime.format(formatter);
        return res;
    }
}
